﻿using Microsoft.Extensions.DependencyInjection;
using System.Data.Common;
using System.Threading.Tasks;
namespace Gaea
{
    internal class GaeaConnectionFactory : IGaeaConnectionFactory
    {
        private IGaeaOptionCache _gaeaConnectionFactoryOptionCache;

        public GaeaConnectionFactory()
        {
            _gaeaConnectionFactoryOptionCache = GaeaExtension.ServiceProviderRoot.GetRequiredService<IGaeaOptionCache>();
        }

        public async Task<DbConnection> GetConnectionAsync(IGaeaPower gaeaPower, bool needOpen = true)
        {
            var gaeaOption = _gaeaConnectionFactoryOptionCache.GetOption(gaeaPower.GetType());

            var serviceProviderScope = GaeaExtension.ServiceProviderRoot.CreateScope();
            var dbConnection = serviceProviderScope.ServiceProvider.GetRequiredService(gaeaOption.TypeOfDbConnection) as DbConnection;

            dbConnection.ConnectionString = gaeaOption.ConnectionString;
            if (needOpen)
            {
                await dbConnection.OpenAsync();
            }
            return dbConnection;
        }

        public DbConnection GetConnection(IGaeaPower gaeaPower, bool needOpen = true)
        {
            var gaeaOption = _gaeaConnectionFactoryOptionCache.GetOption(gaeaPower.GetType());

            var serviceProviderScope = GaeaExtension.ServiceProviderRoot.CreateScope();
            var dbConnection = serviceProviderScope.ServiceProvider.GetRequiredService(gaeaOption.TypeOfDbConnection) as DbConnection;
            dbConnection.ConnectionString = gaeaOption.ConnectionString;
            if (needOpen)
            {
                dbConnection.Open();
            }
            return dbConnection;
        }
    }
}
